package com.carol.lmsbe.controller;

import com.carol.lmsbe.common.Result;
import com.carol.lmsbe.dto.LoginRequest;
import com.carol.lmsbe.dto.LoginResponse;
import com.carol.lmsbe.dto.UserDTO;
import com.carol.lmsbe.security.JwtAuthenticationFilter;
import com.carol.lmsbe.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;

/**
 * 认证控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/auth")
@RequiredArgsConstructor
public class AuthController {

    private final UserService userService;

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public Result<LoginResponse> login(@Valid @RequestBody LoginRequest loginRequest) {
        try {
            LoginResponse response = userService.login(loginRequest);
            return Result.success("登录成功", response);
        } catch (Exception e) {
            log.error("登录失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取当前用户信息
     */
    @GetMapping("/me")
    public Result<UserDTO> getCurrentUser() {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            if (authentication == null) {
                return Result.unauthorized("未登录");
            }
            
            // 从认证对象中获取用户ID
            Long userId = null;
            if (authentication.getDetails() instanceof JwtAuthenticationFilter.UserPrincipal) {
                JwtAuthenticationFilter.UserPrincipal userPrincipal = 
                    (JwtAuthenticationFilter.UserPrincipal) authentication.getDetails();
                userId = userPrincipal.getUserId();
            } else {
                // 如果没有UserPrincipal，尝试从用户名获取用户ID
                String username = authentication.getName();
                com.carol.lmsbe.entity.User user = userService.getUserByUsername(username);
                if (user != null) {
                    userId = user.getId();
                }
            }
            
            if (userId == null) {
                return Result.unauthorized("未登录");
            }
            
            UserDTO userInfo = userService.getCurrentUserInfo(userId);
            return Result.success(userInfo);
        } catch (Exception e) {
            log.error("获取用户信息失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 用户登出
     */
    @PostMapping("/logout")
    public Result<Void> logout() {
        // JWT是无状态的，登出只需要前端删除token即可
        return Result.success();
    }
}
